package assingment.cortica.artem.barger;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

/**
 * Class to download and resize requested image.
 * 
 * @author Artem Barger
 *
 */
public class Downloader implements Runnable {

	private static final String RESIZERS_WIDTH = "resizers.width";

	private static final String RESIZERS_HEIGHT = "resizers.height";

	private static final String DOWNLOADERS_IMAGE_DOWNLOADED_FOLDER = "downloaders.image.downloaded.folder";

	private URL imageToDownload;

	private String dowloadedFolder;

	private String fileName;
	
	private Logger log = Logger.getLogger( Downloader.class);
	
	private int image_height;
	
	private int image_width;
	
	public Downloader( final URL imageToDownload) {
		this.imageToDownload = imageToDownload;
		Properties properties = new Properties( );
		Pattern pattern = Pattern.compile( "[A-Za-z0-9:\\/_+\\-]*?.\\/([_+A-Za-z0-9\\-]*.jpg)");
		Matcher matcher = pattern.matcher( imageToDownload.getFile( ));
		if (matcher.find( )) {
			fileName = matcher.group(1);
		}
		try {
			properties.load( Downloader.class.getClassLoader().getResourceAsStream( "cortica.properties"));
			dowloadedFolder = properties.getProperty( DOWNLOADERS_IMAGE_DOWNLOADED_FOLDER, "downloaded");
			image_height = Integer.valueOf( properties.getProperty( RESIZERS_HEIGHT, "100"));
			image_width = Integer.valueOf( properties.getProperty( RESIZERS_WIDTH, "100"));
		} catch (IOException e) {
			log.error( e);
		}
	}
	
	@Override
	public void run() {
		// No file to download
		if ( null == fileName) 
			return;
	    try {
			BufferedImage image = ImageIO.read(imageToDownload);
			log.info( "Image " + imageToDownload.getFile( ) + " has been downloaded.");
			int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
			ImageIO.write( resizeImage(image, type), "jpg", new File( dowloadedFolder + fileName));
			log.info( "Image " + imageToDownload.getFile( ) + " has been resized.");
			DBManager manager = new DBManager( );
			manager.insertRecord( dowloadedFolder + fileName, imageToDownload.getFile( ));
		} catch (IOException e) {
			log.error( e);
		}
	}
	
    /**
     * @param originalImage image to be resized
     * @param type
     * @return resized image according to the properties file.
     */
    private BufferedImage resizeImage(BufferedImage originalImage, int type){
    	BufferedImage resizedImage = new BufferedImage(image_width, image_height, type);
    	Graphics2D g = resizedImage.createGraphics();
    	g.drawImage(originalImage, 0, 0, image_width, image_height, null);
    	g.dispose();
    	return resizedImage;
    }
}